package com.intgrt.manager.ctrl;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.intgrt.manager.entity.SysUser;
import com.intgrt.manager.util.ProjectConstants;
import com.intgrt.manager.util.ProjectTools;
import com.intgrt.manager.util.UserInfo;

@Controller
public class LoginCtrl {
	
	private static Log logger = LogFactory.getLog(LoginCtrl.class);
	
	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String login(HttpServletRequest request) {
		return "login";
	}

	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public String login(HttpServletRequest request, SysUser user) {
		Subject subject = SecurityUtils.getSubject();
		user.setAccpsw(ProjectTools.md5Encode(user.getAccpsw()));

		UsernamePasswordToken token = new UsernamePasswordToken(user.getAcccode(), user.getAccpsw());
		try {
			subject.login(token);
			HttpSession session = request.getSession();
			SysUser curuser = UserInfo.getUser();
			curuser.setAccpsw("");
			session.setAttribute(ProjectConstants.SESSION_USER, curuser);
		} catch (AuthenticationException e) {
			logger.warn("登陆失败");
			request.setAttribute("status", ProjectConstants.ERROR_CODE_USERNAME_PASSWORD_MISMATCH);
			request.setAttribute("msg", "账号或密码错误");
			return "error";
		}
		return "redirect:/";
	}
}
